package com.heima.article.interceptor;

import com.heima.common.dto.User;

import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 需求分析
        // 从请求头中获取用户id
        String userIdStr = request.getHeader("userId");
        // 放入到本地线程中
        if (!StringUtils.isEmpty(userIdStr) && !userIdStr.equals("0")) {
            Integer userId = Integer.parseInt(userIdStr);
            User user = new User(userId);
            MediaThreadLocalUtil.set(user);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MediaThreadLocalUtil.remove();
    }
}
